package com.tpc.control.config;

import java.io.IOException;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;


public class LoginFilter implements Filter {
	private String timeoutPage = "con000/con000.faces";
	
	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest)servletRequest; 
		HttpServletResponse response = (HttpServletResponse)servletResponse; 
		
		if (isSessionControlRequiredForThisResource(request)) {
			String timeoutUrl = request.getContextPath() + "/" + timeoutPage;
			if (isSessionInvalid(request)) {
				System.out.println("Session is invalid! redirecting to timeoutpage : " + timeoutUrl);
				response.sendRedirect(timeoutUrl);
				return;
			} 
		}
		/* deliver request to next filter */
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}
	
	private boolean isSessionControlRequiredForThisResource(HttpServletRequest httpServletRequest) {

		String requestPath = httpServletRequest.getRequestURI();
		boolean controlRequired = !StringUtils.contains(requestPath, timeoutPage);

		return controlRequired;

	}
	private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {

		boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null)

				&& !httpServletRequest.isRequestedSessionIdValid();
		return sessionInValid;

		}

}
